package com.smec;

import java.sql.*;

/**
 * @ClassName MySQLTest
 * @Description TODO
 * @Author u3431
 * @Date 2022/1/17 8:33
 * @Version 1.0
 */
public class MySQLTest {
    static final String JDBC_DRIVER = "com.mysql.cj.jdbc.Driver";
    static final String DB_URL = "jdbc:mysql://localhost:3306/test?" +
            "useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=UTC";
    static final String USER = "root";
    static final String PASS = "123456";

    public static void main(String[] args) {
        Connection conn= null;
        Statement stmt = null;
        try {
            Class.forName(JDBC_DRIVER);
            System.out.println("连接数据库...");
            conn = DriverManager.getConnection(DB_URL, USER, PASS);

            System.out.println("实例化statement对象");
            stmt =conn.createStatement();
            String sql;

            sql = "INSERT INTO\n" +
                    "new_table(id, name)\n" +
                    "values(3,'王5');";
            stmt.executeUpdate(sql);
            sql = "SELECT * FROM new_table";
            ResultSet rs = stmt.executeQuery(sql);
            while (rs.next()){
                int id = rs.getInt("id");
                String name = rs.getString("name");

                System.out.println("id:" + id +"; " + "name:" + name);
            }
            rs.close();
            stmt.close();
            conn.close();
        }catch (ClassNotFoundException | SQLException ce){
            ce.printStackTrace();
        } finally {
            try{
                if(stmt!=null) stmt.close();
            }catch(SQLException ignored){
            }// 什么都不做
            try{
                if(conn!=null) conn.close();
            }catch(SQLException se){
                se.printStackTrace();
            }
        }
    }
}
